﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCM.UI.ChildWindows;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.ZNH.ZMCM.UI.Utils;

//对应ServiceZMCM01.java
namespace Baosight.ZNH.ZMCM.UI
{

    /// <summary>
    /// 系统模块，树形结构 
    /// </summary>
    /// Title:ZMCM01，ServiceZMCM01
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 杨鸣
    /// Version: 1.0
    /// History:
    ///       2011-05-26  杨鸣   [创建]
    ///
    public partial class ZMCM01 : EFViewCmes
    {
        private EFTreeItem item;    //记录选中的树节点
        private EIBlock mcblock;
        private BaseBlock baseBlock = new BaseBlock();//构造前台是否下拉列表
        private String myMod = "";//
        public ZMCM01()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ZMCM01_Loaded);
        }

        public override void Initialize(EIInfo initData)
        {
            base.Initialize(initData);
            base.BeforeAction += OnBeforeAction;
            mcblock = initData.GetBlock("cmes.cm.materialClassify");
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ZMCM01_Loaded(object sender, RoutedEventArgs e)
        {
            this.materialTypeTree.Refresh();
        }

        /// <summary>
        /// 获取tree选中的结点对应的label
        /// </summary>
        /// <param name="tree"></param>
        /// <returns></returns>
        private Dictionary<string, string> getTreeNodeInfo(EFTreeItem item)
        {

            string label = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
            string text = item.ItemObject.GetType().GetProperty("text").GetValue(item.ItemObject, null) as string;
            string isLeaf = (item.IsLeaf == true) ? "1" : "0";
            string fdKeyId = item.ItemObject.GetType().GetProperty("fdKeyId").GetValue(item.ItemObject, null) as string;
            string fdTypeCode = item.ItemObject.GetType().GetProperty("fdTypeCode").GetValue(item.ItemObject, null) as string;
            string fdTypeInnerCode = item.ItemObject.GetType().GetProperty("fdTypeInnerCode").GetValue(item.ItemObject, null) as string;
            string fdTypeAllCode = item.ItemObject.GetType().GetProperty("fdTypeAllCode").GetValue(item.ItemObject, null) as string;
            string fdTypeName = item.ItemObject.GetType().GetProperty("fdTypeName").GetValue(item.ItemObject, null) as string;
            string fdMaterialClassify = item.ItemObject.GetType().GetProperty("fdMaterialClassify").GetValue(item.ItemObject, null) as string;

            int intfdTypeLevel = (int)item.ItemObject.GetType().GetProperty("fdTypeLevel").GetValue(item.ItemObject, null);
            string fdTypeLevel = intfdTypeLevel.ToString();
            string fdParentId = item.ItemObject.GetType().GetProperty("fdParentId").GetValue(item.ItemObject, null) as string;
            int intfdIsAddmaterial = (int)item.ItemObject.GetType().GetProperty("fdIsAddmaterial").GetValue(item.ItemObject, null);
            string fdIsAddmaterial = intfdIsAddmaterial.ToString();

            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("label", label);
            args.Add("text", text);
            args.Add("isLeaf", isLeaf);
            args.Add("treeKeyId", fdKeyId);
            args.Add("treeTypeCode", fdTypeCode);
            args.Add("treeTypeInnerCode", fdTypeInnerCode);
            args.Add("treeTypeAllCode", fdTypeAllCode);
            args.Add("treeTypeName", fdTypeName);
            args.Add("treeMaterialClassify", fdMaterialClassify);
            args.Add("treeTypeLevel", fdTypeLevel);
            args.Add("treeParentId", fdParentId);
            args.Add("treeIsAddmaterial", fdIsAddmaterial);

            //if (item.IsLeaf == false)
            //{
            //    args.Add("label", label);
            //    args.Add("text", text);
            //}

            return args;
        }

        /// <summary>
        /// 重新基类的发布数据方法
        /// 刷新树节点
        /// </summary>
        /// <param name="data"></param>
        public override void OnEIDataPublished(Platform.Core.EIInfo data)
        {
            Dictionary<string, string> args = new Dictionary<string, string>();
            string _value = "";
            if (item != null)
            {
                if (item.IsLeaf || myMod.Equals("update") || myMod.Equals("delete"))
                {
                    _value = (item.Parent as EFTreeItem).ItemObject.GetType().GetProperty("label").GetValue((item.Parent as EFTreeItem).ItemObject, null) as string;
                    args.Add("node", _value);
                }
                else
                {
                    _value = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
                    args.Add("node", _value);
                }
            }
            BaseTools.RefreshTree("ZMCM01", "query", args, OnDoWorkCompleted);
        }

        /// <summary>
        /// OnDoWorkCompleted回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            this.materialTypeTree.EIDataContext = new Platform.Core.UI.EIDataContext();
            this.materialTypeTree.EIDataContext.Update(e.EIInfo);
            item.IsLoadOnDemandEnabled = true;
            if (item.IsLeaf || myMod.Equals("update") || myMod.Equals("delete"))
            {
                EFTreeItem parent = item.Parent as EFTreeItem;
                string node = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
                parent.Items.Clear();
                parent.CollapseItem();
                parent.ExpandItem();
                item = BaseTools.FindTreeItem(parent.Items, node, "label") as EFTreeItem;
                if (item == null)//如果为删除，则选中上级节点
                {
                    this.materialTypeTree.SelectedItem = parent;
                }
                this.materialTypeTree.SelectedItem = item;
                return;
            }
            item.Items.Clear();
            item.CollapseItem();
            item.ExpandItem();
        }

        /// <summary>
        /// 第一次进入页面时选中树的根节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void materialTypeTree_ItemPrepared(object sender, Telerik.Windows.Controls.RadTreeViewItemPreparedEventArgs e)
        {
            if (e.PreparedItem == null)
            {
                return;
            }
            EFTreeItem treeItem = e.PreparedItem as EFTreeItem;

            string label = treeItem.ItemObject.GetType().GetProperty("label").GetValue(treeItem.ItemObject, null) as string;
            if (treeItem.Level == 0 && label.Equals("root"))
            {
                this.materialTypeTree.SelectedItem = treeItem;//选中
                treeItem.ExpandItem();//展开
            }
        }


        /// <summary>
        /// 选中树节点，导航右侧的页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void materialTypeTree_Selected(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            item = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
            Dictionary<string, string> args = getTreeNodeInfo(item);

            int treeIsAddmaterial = int.Parse(args["treeIsAddmaterial"]);
            int treeTypeLevel = int.Parse(args["treeTypeLevel"]);

            if (treeTypeLevel == 4)
            {//如果是第三级，就隐藏新增按钮，不能新增更小类
                Button insertbut = this.FindName("INSERT") as Button;
                if (insertbut != null)
                    insertbut.IsEnabled = false;
            }
            else {
                Button insertbut = this.FindName("INSERT") as Button;
                insertbut.IsEnabled = true;
            }

            //if (item.IsLeaf == true )
            //{
            //    this.container.LoadView<EFCustomViewContainerPanel>("ZMCM02", args);
            //}

            //if (treeTypeLevel == 0)//当为根节点时不用InnerCode过滤
            //{
            //    if (args.ContainsKey("treeTypeInnerCode")){
            //        args.Remove("treeTypeInnerCode");
            //    }
            //    args.Add("treeTypeInnerCode", "");
            //}

            //方便以后修改 下列判断的结果是一样的
            if (item.IsLeaf == true && treeIsAddmaterial == 1)
            {
                this.container.LoadView<EFCustomViewContainerPanel>("ZMCM02", args);
            }
            else
            {
                this.container.LoadView<EFCustomViewContainerPanel>("ZMCM02", args);
            }
        }

        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            item = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
            Dictionary<string, string> args = getTreeNodeInfo(item);

            String treeTypeLevel = args["treeTypeLevel"].ToString();

            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;
            if (this.materialTypeTree.SelectedItem == null)
            {
                EFWindow.Alert("请选中需要操作的节点");
                base.TempButtonOpen(true);
            }
            //else if (treeTypeLevel.Trim() == "3" || treeTypeLevel.Trim().Equals("3"))
            //{
            //    EFWindow.Alert("该层已是小类~~~~~");
            //    base.TempButtonOpen(true);
            //}
            else
            {
                EIInfo eiInfo = new EIInfo();
                myMod = "insert";
                this.OpenWindows(eiInfo, "物资分类-新增", "insert");
            }
            //base.OnInsertButtonClickPopup(sender, e, eiInfo, "物资分类-新增", "insert");
        }

        /// <summary>
        /// 修改前设置属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = new List<EIRow>();
            //_view.Args.Add("fdParentId", this.fdParentId.GetDataValue().ToString());

            base.ViewProperty = _view;

        }

        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;

            EIInfo eIInfo = new EIInfo();
            eIInfo.Set(EIConstants.ServiceNameKey, "ZMCM01");
            eIInfo.Set(EIConstants.MethodNameKey, "delete");
            EFTreeItem treeItem = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
            string fdKeyId = treeItem.ItemObject.GetType().GetProperty("fdKeyId").GetValue(item.ItemObject, null) as string;
            string fdTypeInnerCode = treeItem.ItemObject.GetType().GetProperty("fdTypeInnerCode").GetValue(item.ItemObject, null) as string;
            string fdParentId = treeItem.ItemObject.GetType().GetProperty("fdParentId").GetValue(item.ItemObject, null) as string;
            
            if (treeItem == null)
            {
                base.OpenEFWindowAlert("请选择需要删除的记录！",true);
                base.TempButtonOpen(true);
                return;
            }
            else
            {
                if (fdTypeInnerCode.Equals("root"))//不能删除物资分类根节点
                {
                    base.OpenEFWindowAlert("不能删除默认节点！", true);
                    base.TempButtonOpen(true);
                    return;
                }
                else {
                    if (fdTypeInnerCode.StartsWith("del"))//不能删除作废分类及作废分类下的材料分类
                    {
                        base.OpenEFWindowAlert("不能删除作废分类及作废分类下的材料分类！", true);
                        base.TempButtonOpen(true);
                        return;
                    }else{
                        DialogParameters param = this.ModelDialogParameters("Confirm", "确定删除该分类吗？");
                        param.Closed = OnDeleteConfirmClosed;
                        EFWindow.Confirm(param);
                    }
                }
            }
        }

        /// <summary>
        /// 修改确认，点击修改按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDeleteConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，按钮生效
                return;
            }

            if (e.DialogResult.Value)
            {
                EIInfo eIInfo = new EIInfo();
                eIInfo.Set(EIConstants.ServiceNameKey, "ZMCM01");
                eIInfo.Set(EIConstants.MethodNameKey, "delete");
                EFTreeItem treeItem = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
                string fdKeyId = treeItem.ItemObject.GetType().GetProperty("fdKeyId").GetValue(item.ItemObject, null) as string;
                string fdTypeInnerCode = treeItem.ItemObject.GetType().GetProperty("fdTypeInnerCode").GetValue(item.ItemObject, null) as string;
                string fdParentId = treeItem.ItemObject.GetType().GetProperty("fdParentId").GetValue(item.ItemObject, null) as string;
                eIInfo.Set("fdKeyId", fdKeyId);
                eIInfo.Set("fdTypeInnerCode", fdTypeInnerCode);
                eIInfo.Set("fdParentId", fdParentId);
                myMod = "delete";
                base.Submit(eIInfo, ThisDeleteOperationCompleted);
            }
        }

        private void ThisDeleteOperationCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                String msg = "删除失败！";
                if(e.EIInfo.GetMsg()!= null || e.EIInfo.GetMsg().Equals("")){
                    msg = e.EIInfo.Msg;
                }
                base.OpenEFWindowAlert(msg, true);
                base.TempButtonOpen(true);
            }
            else
            {
                this.OnEIDataPublished(e.EIInfo);

                Dictionary<string, string> args = new Dictionary<string, string>();
                this.container.LoadView<EFCustomViewContainerPanel>("ZMCM02", args);
                
                base.TempButtonOpen(true);
            }
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;

            EIInfo eiInfo = new EIInfo();
            EFTreeItem treeItem = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
            string fdTypeInnerCode = treeItem.ItemObject.GetType().GetProperty("fdTypeInnerCode").GetValue(item.ItemObject, null) as string;
            if (treeItem == null)
            {
                base.OpenEFWindowAlert("请选择需要修改的记录！", true);
                return;
            }
            if (fdTypeInnerCode.Equals("root"))//不能修改物资分类根节点
            {
                base.OpenEFWindowAlert("不能修改默认节点！", true);
                return;
            }
            if (fdTypeInnerCode.StartsWith("del"))//不能修改作废分类及作废分类下的材料分类
            {
                base.OpenEFWindowAlert("不能修改作废分类及作废分类下的材料分类！", true);
                return;
            }

            string fdKeyId = treeItem.ItemObject.GetType().GetProperty("fdKeyId").GetValue(item.ItemObject, null) as string;
            string fdParentId = item.ItemObject.GetType().GetProperty("fdParentId").GetValue(item.ItemObject, null) as string;
            eiInfo.Set("service", "ZMCM01");
            eiInfo.Set("fdKeyId", fdKeyId);
            eiInfo.Set("method", "getMaterialTypeByID");
            
            myMod = "update";

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, GetMaterialTypeCompleted);

            ////EFViewCmesProperty _view = new EFViewCmesProperty();
            ////_view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            ////base.ViewProperty = null;
            ////base.ViewProperty = _view;     //不能使用OnBeforeAction方法，在这里赋值
            //EFTreeItem treeItem = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
            ////EIRow row = (treeItem.Item as UIBaseEntity).GetEIRow();
            ////IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            ////EIRow row = _list.Count > 0 ? _list[0] : new EIRow();

            //EIInfo eiInfo = new EIInfo();
            //EIBlock eIBlock = new EIBlock("result");
            //EIRow row = new EIRow();

            //eIBlock.SetColumns(base.CacheEIInfo.GetBlock("result").GetColumns());
            //eIBlock.SetRow(0, row);
            //eiInfo.AddBlock(eIBlock);

            //base.OnUpdateButtonClickPopup(sender, e, eiInfo, "物资分类-修改", "update");
        }

        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetMaterialTypeCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() != -1)
            {
                this.OpenWindows(e.EIInfo, "物资分类-修改", "update");
            }
            else
            {
                base.OpenEFWindowAlert(e.EIInfo.GetMsg(), true);
                base.TempButtonOpen(true);
            }
        }

        /// <summary>
        /// 点击作废/激活事件 功能已取消，此方法已不用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnModifyButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            int count = this.ViewProperty.EFGridCheckedRows.Count;

            //更新新版本后此处需要修改
            //if (count <= 0)
            //{
            //    base.OpenEFWindowAlert("请选择一条记录进行修改！", true);
            //    return;
            //}
            //else if (count > 1)
            //{
            //    base.OpenEFWindowAlert("最多只能选择一条记录进行修改！", true);
            //    return;
            //}
            //else
            //{
            base.OnModifyButtonClick("ZMCM01", "modifyMaterialStatus", "修改", sender, e);
            //}

        }


        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public void OpenWindows(EIInfo eIInfo, string title, string dialogType)
        {

            item = this.materialTypeTree.SelectedItems[0] as EFTreeItem;
            Dictionary<string, string> args = getTreeNodeInfo(item);

            MaterialType materialType = new MaterialType(dialogType);//构造一个新的修改页面
            materialType.EIDataContext = new Platform.Core.UI.EIDataContext();
            //outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cl.noteSource"));
            eIInfo.AddBlock(mcblock);//模块状态 再用|停用
            eIInfo.AddBlock(baseBlock.GetYesOrNo());//是否下拉框
            materialType.EIDataContext.Update(eIInfo);//数据渲染

            if (dialogType.Equals("insert"))
            {
                if (!args["treeTypeLevel"].Equals("0"))
                {
                    materialType.fdSum.Visibility = Visibility.Collapsed;
                }
                //  materialType.isLeaf.Value = this.isLeaf.Value;//是否叶子节点
                //int moduleLevel = Convert.ToInt16(this.fdParentLevel.Value == null ? 0 : this.fdParentLevel.Value) + 1;
                //MaterialType.SetModuleLevelName(moduleLevel.ToString());//模块级别名称
                materialType.fdParentLevel.Value = args["treeTypeLevel"];
                materialType.isLeaf.Value = args["isLeaf"];
                materialType.fdParentTypeInnerCode.Value = args["treeTypeInnerCode"];
                int fdParentLevel = Convert.ToInt16(args["treeTypeLevel"]) + 1;
                materialType.fdTypeLevel.Value = fdParentLevel;
                materialType.fdParentId.Value = args["treeKeyId"]; //父级ID

                materialType.fdParentTypeCode.Value = args["treeTypeCode"];
                materialType.fdParentTypeName.Value = args["treeTypeName"];
            }
            else
            {
                if (!args["treeTypeLevel"].Equals("1"))
                {
                    materialType.fdSum.Visibility = Visibility.Collapsed;
                }
                if (dialogType.Equals("update"))
                {
                    //materialType.fdKeyId.Value = args["fdKeyId"];
                    //materialType.fdTypeCode.Value = args["fdTypeCode"];
                    //materialType.fdTypeInnerCode.Value = args["fdTypeInnerCode"];
                    //materialType.fdTypeName.Value = args["fdTypeName"];
                    //materialType.fdMaterialClassify.Value = args["fdMaterialClassify"];
                    //materialType.fdTypeLevel.Value = args["fdTypeLevel"];
                    //materialType.fdParentId.Value = args["fdParentId"];
                    //materialType.fdIsAddmaterial.Value = args["fdIsAddmaterial"];
                }
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = title == null ? "" : title;//设置Title
            _popup.Content = materialType;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(InsertWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Tree区域
                //this.materialTypeTree.Refresh();
                //this.UpdateHomePageData(new EiInfo());

                Dictionary<string, string> args = new Dictionary<string, string>();
                string _value = "";
                if (item != null)
                {
                    //if (item.IsLeaf && dialogType.Equals("update"))
                    if (item.IsLeaf || myMod.Equals("update") || myMod.Equals("delete"))
                    {
                        _value = (item.Parent as EFTreeItem).ItemObject.GetType().GetProperty("label").GetValue((item.Parent as EFTreeItem).ItemObject, null) as string;
                        args.Add("node", _value);
                    }
                    else
                    {
                        _value = item.ItemObject.GetType().GetProperty("label").GetValue(item.ItemObject, null) as string;
                        args.Add("node", _value);
                    }
                }
                BaseTools.RefreshTree("ZMCM01", "query", args, OnDoWorkCompleted);


            }
            //按钮生效
            base.TempButtonOpen(true);
            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }




    }
}
